package com.gui.controller;

import com.gui.exception.DIYExceptionHandler;
import com.gui.mapper.QuestionMapper;
import com.gui.mapper.UserMapper;
import com.gui.model.Question;
import com.gui.model.User;
import com.gui.service.PublishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * PubishController
 *
 * @author guigu
 * @QQ 1170258867
 * @date 2020/5/27
 * @description 跳转到编写文章页面
 */
@Controller
public class PubishController {


    @Autowired
    private UserMapper usermapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private PublishService publishService;

    @GetMapping("/publish")
    public String toPublish(){
        return "publish";
    }

    @GetMapping("/publish/{id}")
    public String toEdit(@PathVariable("id") int id, Model model){
        Question oneQuestion = questionMapper.getOneQuestion(id);
        model.addAttribute("id",oneQuestion.getId());
        model.addAttribute("title",oneQuestion.getTitle());
        model.addAttribute("description",oneQuestion.getDescription());
        model.addAttribute("tag",oneQuestion.getTag());
        return "publish";
    }


    @PostMapping("/publish")
    public String subPublic(
            Question question,
            Model model,HttpServletRequest request) throws DIYExceptionHandler {
        model.addAttribute("title",question.getTitle());
        model.addAttribute("description",question.getDescription());
        model.addAttribute("tag",question.getTag());
        if (question.getTitle().isEmpty()){
            model.addAttribute("error","标题不能为空");
            return "publish";
        }
        if (question.getDescription().isEmpty()){
            model.addAttribute("error","描述不能为空");
            return "publish";
        }
        if (question.getTag().isEmpty()){
            model.addAttribute("error","标签不能为空");
            return "publish";
        }
        User user = (User)request.getSession().getAttribute("user");
        question.setCreator(user.getId());
        publishService.SaveOrupdate(question);
        return "redirect:/";
    }

}
